package com.example.hackernerd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

	private Spinner kind_spinner;
	private Spinner type_spinner;

	private String httpEntityToString (InputStream is)
	{
		String result = null; 
		StringBuilder sb = null;
		
		try{ 
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
			sb = new StringBuilder(); 
			sb.append(reader.readLine() + "\n"); 
			String line="0"; 
			while ((line = reader.readLine()) != null) { 
				sb.append(line + "\n"); 
			} 
			is.close(); 
			result=sb.toString(); 
		}catch(Exception e){ 
			Log.e("log_tag", "Error converting result "+e.toString()); 
		}
		
		return result;
	}

	private InputStream getHttpPost(String url)
	{
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
		InputStream is = null;	

		try{ 
			HttpClient httpclient = new DefaultHttpClient(); 
			HttpPost httppost = new HttpPost(url); 
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
			HttpResponse response = httpclient.execute(httppost); 
			HttpEntity entity = response.getEntity(); 
			is = entity.getContent(); 
		}catch(Exception e){ 
			Log.e("log_tag", "Error in http connection"+e.toString()); 
		}
		
		return is;
	}
	
	private String getServer() {
		kind_spinner = (Spinner) findViewById(R.id.kind_spinner);
		switch (kind_spinner.getSelectedItemPosition()) {
		case 0: return "http://10.0.2.2:8080/demo/hackernerd.php";
		case 1:	return "http://10.0.2.2:8888/fetch";
		default:
			return null;
		}
	}

	private String getWord() {
    	JSONArray jArray; 
    	InputStream is = null; 
        String wd = null; 
        String result = null; 

		//http post
        is = getHttpPost(getServer());
		
        //convert response to string 
        result = httpEntityToString(is);
        
        //paring data 
        try{ 
        	jArray = new JSONArray(result); 
        	JSONObject json_data=null; 
        	for(int i=0;i<1;i++){ 
        		json_data = jArray.getJSONObject(i); 
        		wd=json_data.getString("name"); 
        	} 
        } catch(JSONException e1){ 
        	Toast.makeText(getBaseContext(), "No Word" ,Toast.LENGTH_LONG).show(); 
        } catch (ParseException e1) { 
        	e1.printStackTrace(); 
        } 	
        
        return wd;
	}
	
	private String getURL() {
		String wd = getWord();
		
		kind_spinner = (Spinner) findViewById(R.id.kind_spinner);
		type_spinner = (Spinner) findViewById(R.id.type_spinner);
		
		switch (kind_spinner.getSelectedItemPosition()) {
		case 0:
			switch (type_spinner.getSelectedItemPosition()) {
			case 0:
				return "http://dict.cn/mini.php?q=" + wd; 
			case 1:	
				return "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/" +
							wd + "?key=f67cd8cf-dc56-4bd6-a27b-560362f1c528";
			default:
				return null;
			}
		case 1:	
			switch (type_spinner.getSelectedItemPosition()) {
			case 0:
				return "http://en.wikipedia.org/wiki/" + wd;
			default:
				return null;
			}
		default:
			return null;
		}
	}
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    @Override
    protected void onStart() {
    	super.onStart();
		addListenerOnSpinnerItemSelection();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
 // Given a string representation of a URL, sets up a connection and gets
    // an input stream.
    private String downloadUrl(String urlString) throws IOException {
    	HttpClient httpClient = new DefaultHttpClient();
    	HttpGet get = new HttpGet(urlString);

    	HttpResponse response = httpClient.execute(get);

    	// Build up result
    	return EntityUtils.toString(response.getEntity());
    }
    
    public void addListenerOnSpinnerItemSelection() {
    	kind_spinner = (Spinner) findViewById(R.id.kind_spinner);
		kind_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
    }

    public void clickGo(View v) {
      	new DownloadTask().execute();
    }
    
    // Implementation of AsyncTask used to download XML feed from stackoverflow.com.
    private class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
        	return getURL();
//            try {
//                return downloadUrl(urls[0]);
 //           } catch (IOException e) {
 //               return getResources().getString(R.string.connection_error);
 //           }
        }

        @Override
        protected void onPostExecute(String result) {
            // Displays the HTML string in the UI via a WebView
            WebView myWebView = (WebView) findViewById(R.id.webview);
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            //myWebView.getSettings().setDefaultTextEncodingName("UTF-8") ;
//            try {  
//                myWebView.loadData(URLEncoder.encode(result, "gb2312"), "text/html", "gb2312");
//            } catch (Exception ex) {  
//                ex.printStackTrace();  
//            }                
            //myWebView.loadDataWithBaseURL(null, result, "text/html", "gbk", null);
            myWebView.loadUrl(result);
        }
    }

}
